﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using ComicIsland.Common;
using ComicIsland.Common.Entities.InterfaceJson;
using ComicIsland.Common.WebHelper;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace ComicIsland.App.Views
{
    public partial class BookStoreChannelMorePage : PhoneApplicationPage
    {

        string subjectId = string.Empty;
        private int pageIndex = 1;
        private bool IsLastPage = false;
        private ComicsList currentSelectedItem = null;

        public BookStoreChannelMorePage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);


            if (!base.NavigationContext.QueryString.ContainsKey("subjectId"))
            {
                base.NavigationService.GoBack();
                return;
            }
            subjectId = base.NavigationContext.QueryString["subjectId"];
            if (string.IsNullOrWhiteSpace(subjectId))
            {
                base.NavigationService.GoBack();
                return;
            }

            test(subjectId);
        }


        void test(string subjectId, int pageIndex = 1)
        {
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/comicslist_v2");
            LogHelper.LogInfo(requestUrl + "\tPageIndex=" + pageIndex, this.GetType(), MethodBase.GetCurrentMethod());
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("sort", 0);
            parameters.Add("pageno", pageIndex);
            parameters.Add("pagesize", 20);
            parameters.Add("subject", subjectId);

            PostClientHelper proxy = new PostClientHelper(parameters);
            proxy.DownloadStringCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    LogHelper.LogError(e.Error.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                    return;
                }

                #region 获取结果处理
                string result = e.Result;

                if (string.IsNullOrWhiteSpace(result))
                {
                    LogHelper.LogError("Result is empty.");
                    //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                    return;
                }
                //
                if (result.StartsWith("exception:"))
                {
                    LogHelper.LogError(result);
                    //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                    return;
                }
                LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                //
                var rootCharacterString = JSONHelper.Deserialize<JsonChannelMoreBase>(result);
                if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.ComicsList != null && rootCharacterString.Info.ComicsList.Count > 0))
                {
                    //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                }
                else
                {
                    var items = rootCharacterString.Info.ComicsList;
                    //this.llsChannelMore.ItemsSource = rootCharacterString.Info.ComicsList;
                    if (items != null && items.Count > 0)
                    {
                        this.Dispatcher.BeginInvoke(() =>
                        {
                            if (this.llsChannelMore.ItemsSource != null && this.llsChannelMore.ItemsSource.Count > 0)
                            {
                                foreach (var item in items)
                                {
                                    this.llsChannelMore.ItemsSource.Add(item);
                                }
                            }
                            else
                            {
                                this.llsChannelMore.ItemsSource = items;
                            }
                        });
                    }
                }

                #endregion 获取结果处理
            };
            proxy.DownloadStringAsync(new Uri(requestUrl, UriKind.Absolute));
        }

        



        // 数据加载的标识
        public bool IsLoading = false;
        // 线程锁的对象
        private object o = new object();
        private void llsChannelMore_ItemRealized(object sender, ItemRealizationEventArgs e)
        {
            // 因为该事件会被多个线程进入，所以添加线程锁，控制下面的代码只能单个线程去执行
            lock (o)
            {
                if (IsLoading)
                    return;
                if (e.ItemKind != LongListSelectorItemKind.Item)
                    return;
                currentSelectedItem = e.Container.Content as ComicsList;
                int selectedIndex = this.llsChannelMore.ItemsSource.IndexOf(currentSelectedItem);
                int total = this.llsChannelMore.ItemsSource.Count;
                if (total - selectedIndex <= 2)
                {
                    // 设置IsLoading为true，在加载数据的过程中，禁止多次进入
                    IsLoading = true;
                    if (IsLastPage)
                    {
                        //this.statusBar.OpenStatusBar(AppResources.DataNoMore);
                        //this.statusBar.CloseStatusBar();
                        // 修改加载的状态
                        IsLoading = false;
                    }
                    else
                    {
                        this.pageIndex += 1;
                        this.test(subjectId, pageIndex);
                        // 修改加载的状态
                        IsLoading = false;
                    }
                }
            }
        }

        private void llsChannelMore_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            ComicsList item = this.llsChannelMore.SelectedItem as ComicsList;
            if (item != null)
            {
                NaviService.Navigate(ComicIslandPage.ComicDetailPage, string.Concat("?comicId=", item.BigbookId));
            }
        }
    }
}